package cn.iocoder.yudao.module.policy.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.policy.entity.InfoDO;
import cn.iocoder.yudao.module.policy.mapper.InfoMapper;
import cn.iocoder.yudao.module.policy.service.InfoService;
import cn.iocoder.yudao.module.policy.vo.info.InfoPageReqVO;
import cn.iocoder.yudao.module.policy.vo.info.InfoRespVO;
import cn.iocoder.yudao.module.policy.vo.info.InfoSaveReqVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.POLICY_CREATE_PARAM_MISSING;

/**
 * 就业政策 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class InfoServiceImpl implements InfoService {

    @Resource
    private InfoMapper infoMapper;

    @Override
    public Long createInfo(InfoSaveReqVO createReqVO) {
        // 插入
        InfoDO info = BeanUtils.toBean(createReqVO, InfoDO.class);
        infoMapper.insert(info);
        // 返回
        return info.getPolicyId();
    }

    @Override
    public void updateInfo(InfoSaveReqVO updateReqVO) {
        // 校验存在
        validateInfoExists(updateReqVO.getPolicyId());
        // 更新
        InfoDO updateObj = BeanUtils.toBean(updateReqVO, InfoDO.class);
        infoMapper.updateById(updateObj);
    }

    @Override
    public void deleteInfo(Long id) {
        // 校验存在
        validateInfoExists(id);
        // 删除
        infoMapper.deleteById(id);
    }

    private void validateInfoExists(Long id) {
        if (infoMapper.selectById(id) == null) {
            throw exception(POLICY_CREATE_PARAM_MISSING);
        }
    }

    @Override
    public InfoDO getInfo(Long id) {
        return infoMapper.selectById(id);
    }

    @Override
    public PageResult<InfoDO> getInfoPage(InfoPageReqVO pageReqVO) {
        return infoMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InfoDO> getInfoList(InfoRespVO pageReqVO) {
        LambdaQueryWrapper<InfoDO> like = new LambdaQueryWrapper<InfoDO>();
        if(StrUtil.isNotBlank( pageReqVO.getPolicyTitle())){
            like.like(InfoDO::getPolicyTitle, pageReqVO.getPolicyTitle());
        }
        List<InfoDO> infoDOS = infoMapper.selectList(like);
        if(CollUtil.isNotEmpty(infoDOS)){
            return infoDOS;
        }else {
            return new ArrayList<>();
        }
    }

}